﻿using System;
using System.Text;
using System.Web.Script.Serialization;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.Abstractions;

namespace RoketSolutions.SP2010.Infrostructure.UI.Ajax.ActionResults
{
    public class JsonResult : ActionResult
    {
        public Object Data
        {
            get; 
            set;
        }

        public Encoding Encoding
        {
            get; 
            set;
        }

        public JsonResult(Object data)
        {
            Data = data;
        }

        public JsonResult(Object data, Encoding encoding)
        {
            Data = data;
            Encoding = encoding;
        }

        public override void Execute(ControllerContext context)
        {
            if(context != null)
            {
                var response = context.HttpContext.Response;

                response.ContentType = "application/json";

                if (Encoding != null)
                    response.ContentEncoding = Encoding;

                if(Data != null)
                    response.Write(new JavaScriptSerializer().Serialize(Data));
            }
        }
    }
}
